﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using CoreEx.Common.Extensions;
using CoreEx.DynamicInvoker;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;
using LinFu.IoC;
namespace CoreEx.Common.Repository.Implementation
{        
    [Serializable]
    public class TrackableBindingList<T> : BindingList<T>, IInitialize
    {
        [NonSerialized]
        private IServiceContainer _serviceContainer;
        [NonSerialized]
        private object _listOwner;
        [NonSerialized]
        private IStateTracker _stateTracker;
        
       
        public TrackableBindingList(object listOwner, IStateTracker stateTracker)
        {
            _listOwner = listOwner;
            _stateTracker = stateTracker;
        }

      

        protected override void OnListChanged(ListChangedEventArgs e)
        {
            base.OnListChanged(e);
            if (e.ListChangedType == ListChangedType.ItemAdded)
            {
               _stateTracker.Register(Items[e.NewIndex]);               
                AssignListOwner(Items[e.NewIndex]);
                
            }
        }

        protected override void OnAddingNew(AddingNewEventArgs e)
        {
            base.OnAddingNew(e);
            e.NewObject = _serviceContainer.GetService<T>();
        }


        public void Initialize(IServiceContainer source)
        {
            _serviceContainer = source;
        }

     


     

        protected virtual void AssignListOwner(T target)
        {
            if (_listOwner == null)
                return;

            var listOwnerType = _listOwner.GetType();

            var property = target.GetType().GetProperties().Where(p => p.PropertyType.IsAssignableFrom(listOwnerType)).FirstOrDefault();

            if (property != null)
                property.DynamicInvoke(target, _listOwner);
        }

    }
}
